package cn.lml.lession.auth.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	private final static Logger logger = LoggerFactory.getLogger(WebSecurityConfig.class);

	@Autowired
	private AuthProperties authProperties;
	@Autowired
	private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
	@Autowired
	private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
	@Autowired
	private CustomAccessDeniedHandler customAccessDeniedHandler;
	@Autowired
	private SecurityAuthenticationProvider securityAuthenticationProvider;


    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public PasswordEncoder passwordEncoder()  {
        return new PasswordEncoder() { 
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }
            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(charSequence.toString());
            }
        };
    }
	

    @Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		logger.debug("使用自定义身份验证组件SecurityConfig.configure(AuthenticationManagerBuilder auth)");
		auth.authenticationProvider(securityAuthenticationProvider);
		/* auth.inMemoryAuthentication()
         .withUser("john")
         .password(passwordEncoder().encode("123"))
         .roles("USER");*/
	}

    
    @Override
    public void configure(HttpSecurity http) throws Exception {
      http.csrf().disable()
      	 .requestMatchers()
         .antMatchers("/login**", "/oauth/authorize")
         .and()
         .httpBasic()
         .and()
         .formLogin()
	         .successHandler(customAuthenticationSuccessHandler)
	         .failureHandler(customAuthenticationFailureHandler)
	         .loginPage(authProperties.getAuthLoginUrl())
	         .loginProcessingUrl("/login")
	         .permitAll()
          //配置get不需要验证的URL
         .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET,authProperties.toGetAdapter())
            .permitAll()
          //配置post不需要验证的URL
         .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.POST,authProperties.toPostAdapter())
            .permitAll()
          //除上述URL,都需要登录用户
         .and()
            .authorizeRequests()
            .anyRequest()
            .authenticated()
          //配置用户无权限登录过滤器
         .and()
            .exceptionHandling().accessDeniedHandler(customAccessDeniedHandler);
         //.and()
            //.csrf().disable()
            //.authorizeRequests()
           // .anyRequest()
           //配置授权验证服务
           // .access("@defaultAuthorizationService.hasPermission(request,authentication)");
    }
    
    @Override
	public void configure(WebSecurity web) throws Exception {
	    web.ignoring().antMatchers("/js/**", "/css/**", "/images/**", "/druid/**");
	}

    
}